//
//  FlsTool.m
//  FBSnapshotTestCase
//
//  Created by fls on 2022/4/27.
//

#import "FlsTool.h"
#import "NSDate+Extension.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
@implementation FlsTool
#pragma mark - 截取某一帧的图片
+ (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    
    return thumbnailImage;
}
#pragma mark ---- 获取图片第一帧

+ (UIImage *)backFirstVideoUrl:(NSString * )url{
    NSURL * videoUrl = [NSURL URLWithString:url];
    CGSize imageSize = CGSizeMake(320, 180);
    
    FlsTool * tool = [[FlsTool alloc] init];
    UIImage * firstImage = [tool firstFrameWithVideoURL:videoUrl size:imageSize];
    return firstImage;
}

- (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
{
    // 获取视频第一帧
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(size.width, size.height);
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
    {
        return [UIImage imageWithCGImage:img];
    }
    return nil;
}
#pragma mark ---- 颜色转图片

+ (UIImage *)imageWithColor:(UIColor *)color{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
#pragma mark ---- 去除字符串首尾空格

+ (NSString *)RemoveLeadingTrailingSpacesTheString:(NSString *)string{
    NSString *str = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return str;
}
#pragma mark ---- 去除空格换行符

+ (NSString *)backStringRemoveTheBlankSpaceForString:(NSString *)str{
    
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}
#pragma mark ---- 根据url获取图片

+ (UIImage *)getImageFromURL:(NSString *)fileURL
    {
        UIImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
        result = [UIImage imageWithData:data];
        return result;
    }
#pragma mark ---- 是不是网址

+ (BOOL) IsHttpRule:(NSString *)HttpNumber{
    if (HttpNumber.length <= 0) {
        return NO;
    }
    NSString *regex = @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicate evaluateWithObject:HttpNumber];
    
}
#pragma mark ---- url转码

+ (NSString *)urlEncode:(NSString *)url{
    
    NSLog(@"原url:%@", url);
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              
                                                              (CFStringRef)url,
                                                              
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              
                                                              NULL,
                                                              
                                                              kCFStringEncodingUTF8));
    
    NSLog(@"转码url:%@",  encodedString);
    return encodedString;
    
    
}
#pragma mark ---- 返回当前显示的Controller
+ (UIViewController *)backTopViewController{
    return [[[FlsTool alloc] init] topViewController];
}

- (UIViewController*)topViewController {
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* nav = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:nav.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}
#pragma mark ---- 获取当地时间

+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

#pragma mark ---- 将字符串转成NSDate类型

+ (NSDate *)dateFromString:(NSString *)dateString {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    return destDate;
}
#pragma mark ---- 传入今天的时间，返回明天的时间
+ (NSString *)GetTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}
#pragma mark ---- 直接返回明天的时间
+ (NSString *)DirectTomorrowDay{
    //获取当前时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    NSDate *destDate= [dateFormatter dateFromString:dateTime];
    NSString * TomorrowDay = [FlsTool GetTomorrowDay:destDate];
    return TomorrowDay;
}
#pragma mark ---- 数组倒序输出
+ (NSMutableArray *)ArrayOutputReverseOrder:(NSMutableArray *)array{
    NSMutableArray * resultsArray = [NSMutableArray arrayWithCapacity:0];
    NSArray *arr = [[array reverseObjectEnumerator] allObjects];
    [resultsArray addObjectsFromArray:arr];
    return resultsArray;
}
#pragma mark ---- 字典转json字符串方法
+(NSString *)convertToJsonDataDictionary:(NSDictionary *)dict

{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}
#pragma mark ---- UIview 画圆角
//corners
//UIRectCornerTopLeft  //上部左角
//UIRectCornerTopRight  //上部右角
//UIRectCornerBottomLeft  //下部左角
//UIRectCornerBottomRight //下部右角
//UIRectCornerAllCorners  // 设置所有的角

+ (void)DrawViewRoundedCornersView:(UIView *)view RoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii{
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corners cornerRadii:cornerRadii];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
    
}
#pragma mark ---- 判断两个日期的大小
/**
 *date01 : 第一个日期
 *date02 : 第二个日期
 *format : 日期格式 如：@"yyyy-MM-dd HH:mm"
 *return : 0（等于）1（大于）-1（小于）
 */

+ (int)compareDate:(NSString*)date01 withDate:(NSString*)date02 toDateFormat:(NSString*)format{
    int num;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:format];
    NSDate*dt01 = [[NSDate alloc]init];
    NSDate*dt02 = [[NSDate alloc]init];
    dt01 = [df dateFromString:date01];
    dt02 = [df dateFromString:date02];
    NSComparisonResult result = [dt01 compare:dt02];
    switch(result){
        case  NSOrderedAscending:{
            num = 1;
        }
            break;
        case NSOrderedDescending:{
            num=-1;
        }
            break;
        case NSOrderedSame:{
            num=0;
        }
            break;
        default:{
            NSLog(@"erorr dates %@, %@", dt02, dt01);
        }
            break;
    }
    return num;
}
#pragma mark ---- 字符串转时间戳
+ (NSString *)getTimeStrWithString:(NSString *)str{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%f",[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;

}
#pragma mark ---- NSDate转 NSString
+ (NSString *)makeDateForString:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *selectDate = [dateFormatter stringFromDate:date];
    return selectDate;

}
#pragma mark ----发送本地推送
+(void)SimulateTestRemotePush{


    //学习任务
    NSDictionary * pushDic = @{@"Role":@"1",
                               @"PushModuleType":@"4",
                               @"SchoolId":@"5e069b1a-9d90-49ed-956c-946e9f934b68",
                               @"SortType":@"0",
                               @"_j_uid":@"53206241985",
                               @"AirClassId":@"0",
                               @"isOnlineSchool":@NO,
                               @"SchoolType":@"0",
                               @"_j_msgid":@"47288001207907817",
                               @"aps":@{@"alert":@"接收作业提醒",
                                        @"badge":@"0",
                                        @"sound":@"default",
                               },
                               @"ClassId":@"556d49a9-146b-45a1-a754-ae7000df251e",
                               @"ClassType":@"1",
                               @"Id":@"23603",
                               @"PushTargetType":@"2",
    };

    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
#pragma mark  去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
    notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    
    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:pushDic];
    notification.userInfo = userInfo;
    
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
#pragma mark ----时间相差天数
+ (int)getDateTimeStart:(NSDate *)startTime endTime:(NSDate *)endTime
{
    NSString *startTimeString = [startTime stringWithFormat:@"yyyy-MM-dd"];
    NSString *endTimeString = [endTime stringWithFormat:@"yyyy-MM-dd"];
    startTimeString =  [startTimeString stringByAppendingString:@" 22:22"];
    endTimeString =[endTimeString stringByAppendingString:@" 22:22"];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"yyyy-MM-dd HH:mm";
    NSDate *startDate = [format dateFromString:startTimeString];
    NSDate *endDate = [format dateFromString:endTimeString];
    
    NSTimeInterval startInterval = [startDate timeIntervalSince1970];
    NSTimeInterval endInterval = [endDate timeIntervalSince1970];
    long long startMilliseconds = startInterval*1;
    long long endMilliseconds = endInterval*1;
    int day = (int)((endMilliseconds - startMilliseconds)/(24*3600));
    return day+1;
}
- (NSString *) stringWithFormat: (NSString *) format
{
    NSDateFormatter *formatter = [NSDateFormatter new];
    //    formatter.locale = [NSLocale currentLocale]; // Necessary?
    formatter.dateFormat = format;
    return [formatter stringFromDate:self];
}
#pragma mark ----当前周的日期范围

/**
 @param firstWeekday 星期起始日
 @param dateFormat 日期格式
 @return 结果字符串
 */
+ (NSString *)currentScopeWeek:(NSUInteger)firstWeekday dateFormat:(NSString *)dateFormat date:(NSDate *)nowDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    // 1.周日 2.周一 3.周二 4.周三 5.周四 6.周五  7.周六
    calendar.firstWeekday = firstWeekday;
    
    // 日历单元
    unsigned unitFlag = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday;
    unsigned unitNewFlag = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *nowComponents = [calendar components:unitFlag fromDate:nowDate];
    // 获取今天是周几，需要用来计算
    NSInteger weekDay = [nowComponents weekday];
    // 获取今天是几号，需要用来计算
    NSInteger day = [nowComponents day];
    // 计算今天与本周第一天的间隔天数
    NSInteger countDays = 0;
    // 特殊情况，本周第一天firstWeekday比当前星期weekDay小的，要回退7天
    if (calendar.firstWeekday > weekDay) {
        countDays = 7 + (weekDay - calendar.firstWeekday);
    } else {
        countDays = weekDay - calendar.firstWeekday;
    }
    // 获取这周的第一天日期
    NSDateComponents *firstComponents = [calendar components:unitNewFlag fromDate:nowDate];
    [firstComponents setDay:day - countDays];
    NSDate *firstDate = [calendar dateFromComponents:firstComponents];
    
    // 获取这周的最后一天日期
    NSDateComponents *lastComponents = firstComponents;
    [lastComponents setDay:firstComponents.day + 6];
    NSDate *lastDate = [calendar dateFromComponents:lastComponents];
    
    // 输出
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dateFormat];
    NSString *firstDay = [formatter stringFromDate:firstDate];
    NSString *lastDay = [formatter stringFromDate:lastDate];
    return [NSString stringWithFormat:@"%@ - %@",firstDay,lastDay];
}
#pragma mark ----返回周几
+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}


#pragma mark ----在当前日期时间加上 某个时间段(传负数即返回当前时间之前x月x日的时间)

/**
 *  ** 在当前日期时间加上 某个时间段(传负数即返回当前时间之前x月x日的时间)
 *
 *  @param year   当前时间若干年后 （传负数为当前时间若干年前）
 *  @param month  当前时间若干月后  （传0即与当前时间一样）
 *  @param day    当前时间若干天后
 *  @param hour   当前时间若干小时后
 *  @param minute 当前时间若干分钟后
 *  @param second 当前时间若干秒后
 *
 *  @return 处理后的时间字符串
 */
+ (NSString *)dateStringAfterlocalDateForYear:(NSInteger)year Month:(NSInteger)month Day:(NSInteger)day Hour:(NSInteger)hour Minute:(NSInteger)minute Second:(NSInteger)second NowDate:(NSString *)nowDateString{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateStyle:NSDateFormatterMediumStyle];
//    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *localDate= [formatter dateFromString:nowDateString];
       NSDateComponents *comps = [[NSDateComponents alloc] init];
       [comps setYear:year];
       [comps setMonth:month];
       [comps setDay:day];
       [comps setHour:hour];
       [comps setMinute:minute];
       [comps setSecond:second];
    NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
       
       NSDate *minDate = [calender dateByAddingComponents:comps toDate:localDate options:0];
       
           
       NSDateComponents *components = [calender components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|kCFCalendarUnitMinute fromDate:minDate];
    NSInteger thisYear=[components year];
    NSInteger thisMonth=[components month];
    NSInteger thisDay=[components day];
    NSInteger thisHour=[components hour];
    NSInteger thisMinute=[components minute];

       NSString *DateTime = [NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld",(long)thisYear,(long)thisMonth,(long)thisDay,(long)thisHour,(long)thisMinute];
       return DateTime;
}


#pragma mark 格式化时间样式 对时间进行补0操作
+(NSString *)FormattingTimeStyle:(NSString *)time{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *localDate= [formatter dateFromString:time];
    NSCalendar  *cal = [ NSCalendar  currentCalendar];
    unsigned int  unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|kCFCalendarUnitMinute|kCFCalendarUnitSecond;
    NSDateComponents  *components = [cal components:unitFlags fromDate:localDate];
    NSInteger thisYear=[components year];
    NSInteger thisMonth=[components month];
    NSInteger thisDay=[components day];
    NSInteger thisHour=[components hour];
    NSInteger thisMinute=[components minute];
    NSInteger thisSecond=[components second];
    NSString *DateTime = [NSString stringWithFormat:@"%02ld-%02ld-%02ld %02ld:%02ld:%02ld",(long)thisYear,(long)thisMonth,(long)thisDay,(long)thisHour,(long)thisMinute,(long)thisSecond];
    return DateTime;

}
#pragma mark 两个时间相差分钟
+ (int)getDateTimeMinutesStart:(NSString *)startTime endTime:(NSString *)endTime
{
    NSDateFormatter *date = [[NSDateFormatter alloc]init];

    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate * startD = [date dateFromString:startTime];

    NSDate * endD = [date dateFromString:endTime];

    NSTimeInterval start = [startD timeIntervalSince1970]*1;

    NSTimeInterval end = [endD timeIntervalSince1970]*1;

    NSTimeInterval value = end - start;
    int  minutes = (int)value /60%60;
    return  minutes;
}
#pragma mark 拼接换算时分秒
+ (NSString *)SplicingConversionMinutesAndSeconds:(NSUInteger)timeCount{
    NSMutableArray * timeArray = [NSMutableArray arrayWithCapacity:0];
    NSUInteger hours = (timeCount / 60 /60);
    NSUInteger minutes = (timeCount / 60) % 60;
    NSUInteger seconds = (timeCount % 60);

    if (hours > 0) {
        [timeArray addObject:[NSString stringWithFormat:@"%ld时",hours]];
    }
    if (minutes > 0) {
        [timeArray addObject:[NSString stringWithFormat:@"%ld分",minutes]];
    }
    if (seconds > 0) {
        [timeArray addObject:[NSString stringWithFormat:@"%ld秒",seconds]];
    }
    NSString * timeString = [timeArray componentsJoinedByString:@""];
    return timeString;
}

@end
